package com.sn.campus.utils;

import com.sn.campus.dao.ShipLocationDao;
import com.sn.campus.entity.ShipLocation;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class GetShipLocation {
    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private ShipLocationDao shipLocationDao;
    public void getDate() {
        System.out.println("获取船位的信息数据！！！！！");
        while (true) {
            String url = "http://api.shipxy.com/apicall/GetSingleShip";

            //船舶编号
            String mmsi = "477998200";

            String k = "61a4b03a372e42afa79f8c5f722ddd31";

            String enc = "1";

//        String timestemp = (new SimpleDateFormat("yyyyMMddHH")).format(new Date());
//
//        String key = MD5.MD5(timestemp);
//        String key = "2005130013492251";
//        System.out.println("获取的KEY"+key);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            Map<String, String> params = new HashMap<String, String>();

            params.put("id", mmsi);
            params.put("k", k);
            params.put("enc", enc);
            JSONObject json = JSONObject.fromObject(params);
//        String json = params.toString();
//        HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(Collections.unmodifiableMap(params),headers);
//        JSONObject post = JSONObject.fromObject(request);

            ResponseEntity<String> entity = restTemplate.postForEntity(url, json, String.class);

            String body = entity.getBody();
            System.out.println(body);
            JSONObject jsonObject = JSONObject.fromObject(body);
            Object data1 = jsonObject.get("data");
            List<ShipLocation> shipLocations = JsonUtils.jsonToList(data1.toString(), ShipLocation.class);
//        System.out.println(shipLocations);
//        tBaseCityDao.insertForeach(tBaseCities);
            shipLocations.forEach(shipLocation -> {
                System.out.println(shipLocation);
                shipLocationDao.insert(shipLocation);
            });
            try {
                Thread.sleep(30*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
